// MongoDB 初始化脚本
// 创建应用数据库和用户

// 切换到应用数据库
db = db.getSiblingDB('appdb');

// 创建应用用户
db.createUser({
  user: 'appuser',
  pwd: 'AppUser2025Secure',
  roles: [
    {
      role: 'readWrite',
      db: 'appdb'
    }
  ]
});

// 创建示例集合和索引
db.createCollection('users');
db.createCollection('products');
db.createCollection('orders');

// 为用户集合创建索引
db.users.createIndex({ "email": 1 }, { unique: true });
db.users.createIndex({ "username": 1 }, { unique: true });
db.users.createIndex({ "createdAt": 1 });

// 为产品集合创建索引
db.products.createIndex({ "name": "text", "description": "text" });
db.products.createIndex({ "category": 1 });
db.products.createIndex({ "price": 1 });

// 为订单集合创建索引
db.orders.createIndex({ "userId": 1 });
db.orders.createIndex({ "status": 1 });
db.orders.createIndex({ "createdAt": 1 });

// 插入示例数据
db.users.insertMany([
  {
    username: "admin",
    email: "admin@example.com",
    role: "administrator",
    createdAt: new Date()
  },
  {
    username: "user1",
    email: "user1@example.com",
    role: "user",
    createdAt: new Date()
  }
]);

db.products.insertMany([
  {
    name: "示例产品1",
    description: "这是一个示例产品",
    category: "electronics",
    price: 99.99,
    stock: 100,
    createdAt: new Date()
  },
  {
    name: "示例产品2",
    description: "另一个示例产品",
    category: "books",
    price: 29.99,
    stock: 50,
    createdAt: new Date()
  }
]);

print('MongoDB 初始化完成！');
print('- 创建了应用数据库: appdb');
print('- 创建了应用用户: appuser');
print('- 创建了示例集合和索引');
print('- 插入了示例数据');
